<?php
/**
 * Created by SendCouponsController.class.php.
 * User: wuxiang
 * Date: 2016/11/10
 * Time: 15:54
 */

namespace Coupons\Controller;


use Common\Controller\AdminbaseController;
use Common\Libiary\CommonBill;
use Common\Libiary\FileCsv;
use Common\Libiary\FileExcel;
use Common\Libiary\LogEX;
use Think\Upload;
use Think\Page;

class CouponsController extends AdminbaseController
{

    const COUPONS_KEY = 'coupons:mobile:key';

    function index()
    {
        $sendCoupon = M('SendCoupon');
        I('get.Mobile') ? $data['Mobile'] = I('get.Mobile') : '';
        I('get.CouponId') ? $data['CouponId'] = I('get.CouponId') : '';
        I('get.Status') ?  $data['Status'] = I('get.Status') : '';
        $count = $sendCoupon->where($data)->count();
        $Page = new Page($count, 20, $data);
        $show = $Page->show();
        $list = $sendCoupon->where($data)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->assign('count', $count);
        $this->assign('Mobile', $data['Mobile']);
        $this->assign('CouponId', $data['CouponId']);
        $this->assign('Status', $data['Status']);
        $this->display();
    }

    function send()
    {
        $this->display();
    }

    function sendCoupon()
    {
        set_time_limit(0);
        $sendCoupon = M('SendCoupon');
        $couponId = I('post.couponId', '', 'intval');
        //excel
        if ($_FILES['file']['tmp_name']) {
            $this->getCsvData($_FILES['file']['tmp_name'],$couponId);
        } else {
            //文本框输入
            $mobile = I('post.mobileSub');
            //手机号去重
            $mobileRes = array_unique($mobile);
            $count = count($mobileRes);
            if ($count > 50) {
                $this->error('导入手机号数量' . $count . ',总数不能大于50,如果大于50，请分批导入', '', 30);
            }

            foreach ($mobileRes as $k => $v) {
                //手机号验证
                if (empty(isTelNumber($v))) {
                    $error['Mobile'] = $v;
                    $error['CouponId'] = $couponId;
                    $error['Status'] = 3;
                    $error['CreateTime'] = time();
                    $formatKey = $sendCoupon->add($error);
                    if ($formatKey) {
                        LogEX::d('手机号格式错误' . '手机号'. $v.'优惠券id'.$couponId, $error);
                    }
                    continue;
                }
                //验证手机号是否是注册用户,如果不是注册用户，注册 15601723362
                $userId = isRegisterUser($v);
                $res = [];
                if (empty($userId)) {
                    //注册
                    $userId = addRegisterUser($v);
                    if (empty($userId)) {
                        $res['Mobile'] = $v;
                        $res['CouponId'] = $couponId;
                        $res['Status'] = 1;
                        $res['CreateTime'] = time();
                        $primaryKey = $sendCoupon->add($res);
                        if ($primaryKey) {
                            LogEX::d('注册失败手机号' . '手机号'. $v.'优惠券id'.$couponId, $res);
                        }
                        continue;
                    }
                }
                //发券处理
                $resCou = [];
                $resCou['Mobile'] = $v;
                $resCou['CouponId'] = $couponId;
                $resCou['Status'] = 2;
                $resCou['UserId'] = $userId;
                $resCou['CreateTime'] = time();
                $couponCode = sendCoupons($userId, $couponId, $v);
                if (empty($couponCode)) {
                    $couponKey = $sendCoupon->add($resCou);
                    if ($couponKey) {
                        LogEX::d('发送失败手机号' . '手机号'. $v.'优惠券id'.$couponId, $resCou);
                    }
                    continue;
                }
                $resCou['Status'] = 0;
                $resCou['CouponCode'] = $couponCode;
                LogEX::d('发送优惠券成功' .'手机号'. $v.'优惠券id'.$couponId.'优惠券码'.$couponCode, $resCou);
            }
        }
        $this->success('', U('Coupons/index'), 30);
    }


    //获取手机号
    function getCsvData($file,$couponId)
    {
        $redis = new \Redis();
        $redis->connect(REDIS_PUSH_TAGS, REDIS_PUSH_TAGS_PORT);
        $redis->auth(REDIS_PUSH_TAGS_AUTH);
        $row = 0;
        $mobile = $mobileArr = [];
        if (($handle = fopen($file, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 20, ',')) !== FALSE) {
                if ($row < 1000) {
                    $mobile[] = [
                        'mobile'=>$data[0],
                        'couponId' => $couponId
                    ];
                }
                ++$row;
                if($row>=1000){
                    //$row 大于10的
                    $row=0;
                    $redis->lPush(self::COUPONS_KEY, json_encode($mobile));
                    $redis->lPush(self::COUPONS_KEY.'test', json_encode($mobile));
                    $mobile=[];
                }
            }
            //$row不足10的
            $redis->lPush(self::COUPONS_KEY, json_encode($mobile));
            $redis->lPush(self::COUPONS_KEY.'test', json_encode($mobile));
            fclose($handle);
        }
    }

    //删除文件
    function delFile($filePath)
    {
        if ($filePath) {
            $date = date('Y-m-d');
            @unlink($filePath);
            @rmdir('./public/upload/' . $date);
        }
    }


    //优惠券信息
    function getCouponsInfo()
    {
        $coupons = I('coupons', '', 'intval');
        //优惠券id
        $couponsInfo = getCouponIdInfo($coupons);
        if ($couponsInfo) {
            CommonBill::echoAjaxJson(1, '获取成功', $couponsInfo);
        } else {
            CommonBill::echoAjaxJson(2, '获取失败', $couponsInfo);
        }
    }

    function uploadFile($filename)
    {
        $savePath = './public/upload/';
        $upload = new Upload();// 实例化上传类
        $upload->exts = array('xlsx', 'xls');// 设置附件上传类型
        $upload->rootPath = $savePath; // 设置附件上传根目录
        // 上传单个文件
        $info = $upload->uploadOne($filename);
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功 获取上传文件信息
            $file = $savePath . $info['savepath'] . $info['savename'];
            return $file;
        }
    }

    function micrFloat()
    {
        return microtime(true);
    }

}